//
//  MyWebView.m
//  7UGame
//
//  Created by 111 on 2017/2/21.
//  Copyright © 2017年 111. All rights reserved.
//

#import "JNCardSDKMyWebView.h"
#import "JNCardSDKLianDongResultVC.h"
#import <WebKit/WebKit.h>
#import "JNCardSDKCardDetailVC.h"
@interface JNCardSDKMyWebView ()<UIWebViewDelegate>{
    NSTimer * _timer;
    NSInteger _count;
    UILabel * _timeLab;
    BOOL _canBack;
}

@property(nonatomic,retain)UIWebView * MyWebView;
@end

@implementation JNCardSDKMyWebView

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.MyWebView];
    [self setProgressView];
    [self webViewRequest];
    
}
//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    self.navigationController.navigationBarHidden = YES;
//}
//
//- (void)viewWillDisappear:(BOOL)animated{
//    [super viewWillDisappear:animated];
//    self.navigationController.navigationBarHidden = NO;
//}
-(void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)createNavigationBar{
    
    UIView * navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, kTopHeight)];
    navView.backgroundColor = ThemeColor;
    [self.view addSubview:navView];
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, kStatusBarHeight, kNavBarHeight, kNavBarHeight)];
    [backBtn addTarget:self action:@selector(leftBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"左箭头"] forState:UIControlStateNormal];
    [navView addSubview:backBtn];
    UILabel * titleLab = [[UILabel alloc]initWithFrame:Frame(IPHONE_WIDTH/2-120, 30, 240, 30)];
    titleLab.textColor = [UIColor whiteColor];
    if (IPHONE_WIDTH==320) {
        titleLab.font = [UIFont systemFontOfSize:17.f];
    }else{
        titleLab.font = Font(18);
    }
    titleLab.text = self.webTitle;
    titleLab.textAlignment = NSTextAlignmentCenter;
    [navView addSubview:titleLab];
    [self.view addSubview:self.MyWebView];
    [self setProgressView];
    [self webViewRequest];
}
-(void)webViewRequest
{
    if (self.webType==2) {
        [_MyWebView loadHTMLString:self.htmlStr baseURL:nil];
    }else{
        //缓存机制
        //        NSString *utf = [_currentWebUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURLRequest * req = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:_currentWebUrl]];
        [_MyWebView loadRequest:req];
    }
    
}

-(UIWebView*)MyWebView{
    if (_MyWebView == nil) {
        _MyWebView = [[UIWebView alloc]initWithFrame:CGRectMake(0, kTopHeight, IPHONE_WIDTH, IPHONE_HEIGHT-kTopHeight)];
        _MyWebView.autoresizesSubviews = YES;//自动调整大小
        _MyWebView.scrollView.scrollsToTop = YES;
        _MyWebView.delegate = self;
        _MyWebView.backgroundColor = [UIColor whiteColor];
        _MyWebView.scrollView.bounces = NO;
        _MyWebView.scalesPageToFit =YES;//自动对页面进行缩放以适应屏幕
        _MyWebView.mediaPlaybackRequiresUserAction = YES;
    }
    return _MyWebView;
}
-(void)setProgressView
{
    //进度条
    _progressFlag = 0;
    _speedFlag = NO;
    
    _progressBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
    _progressBar.frame = CGRectMake(0, kTopHeight, IPHONE_WIDTH, 1);
    _progressBar.backgroundColor = [UIColor clearColor];
    _progressBar.hidden = NO;
    
    _progressBar.tintColor = [UIColor colorWithRed:59/255.0 green:158/255.0 blue:250/255.0 alpha:1];
    _progressBar.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:_progressBar];
}
#pragma mark - Timer
- (void)progressLoading
{
    if (_progressBar.progress >= 1){
        _progressBar.progress = 0.0;
        _progressFlag = 0;
        _speedFlag = NO;
    }
    if (_progressFlag == 1){
        float progress = _progressBar.progress;
        if (_progressBar.progress >0.8 && _speedFlag == NO) {
            progress += 0;
        }else{
            progress +=  0.0005;
        }
        [_progressBar setProgress:progress animated:progress];
        [NSTimer scheduledTimerWithTimeInterval: _speedFlag ? 0.000001 : 0.005
                                         target:self
                                       selector:@selector(progressLoading)
                                       userInfo:nil
                                        repeats:NO];
    }
}
-(void)webViewDidStartLoad:(UIWebView *)webView{
    //进度条开始加载
    _progressFlag = 1;
    _speedFlag = NO;
    [self progressLoading];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString * urlStr = request.URL.absoluteString;
    if ([urlStr containsString: @"https://mcashier.95516.com/mobile/authPay/callback.action"]||[urlStr containsString: @"http://epay.gaohuitong.com:8083/interfaceWeb/appBindCard/dealQbyFrontBindReturn"]) {
        //        if (self.successBlock) {
        //            self.successBlock();
        //        }
        //        [self.navigationController popViewControllerAnimated:YES];
        return YES;
    }else if([urlStr isEqualToString:@"http://www.yuntianpay.net/web/success.html"]){
        
        return NO;
    }else if([urlStr containsString:@"api/openCardCallBack"]){
        _timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerfie) userInfo:nil repeats:YES];
        _count = 5;
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
        UIWindow * w = [UIApplication sharedApplication].delegate.window;
        UIView * v = [[UIView alloc]initWithFrame:Frame(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
        v.backgroundColor = [UIColor colorWithWhite:0.7 alpha:0];
        [self.view addSubview:v];
        _timeLab = [UILabel labelWithTitle:@"银联认证通讯中，请等待...(5s)" color:[UIColor blackColor] fontSize:14 alignment:NSTextAlignmentCenter];
        _timeLab.frame = Frame(0, IPHONE_HEIGHT/2+50, IPHONE_WIDTH, 30);
        
        [w addSubview:_timeLab];
        //        [self notify];
        _canBack = NO;
        
        
        return NO;
    }else{
        return YES;
    }
}
-(void)notify{
    [SVProgressHUD show];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    NSNotification * message = [[NSNotification alloc]initWithName:@"createPlanDirectly" object:self userInfo:nil];
    [center postNotification:message];
}
- (void)timerfie {
    if (_count == 0) {
        [SVProgressHUD dismiss];
        [_timer invalidate];
        [_timeLab removeFromSuperview];
        //        if (self.isGoToSMSVerify) {
        //            JNCardSDKLianDongResultVC * vc = [JNCardSDKLianDongResultVC new];//2018-8-29改为这个控制器
        //            vc.cardModel = self.cardModel;
        //            [self.navigationController pushViewController:vc animated:YES];
        //        }else{
        //            if (self.successBlock) {
        //                self.successBlock();
        //            }
        //        }
        //        [self backClick];//返回界面
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[JNCardSDKCardDetailVC class]]) {
                JNCardSDKCardDetailVC *A =(JNCardSDKCardDetailVC *)controller;
                [self.navigationController popToViewController:A animated:YES];
            }
        }
    }
    _count--;
    _timeLab.text = [NSString stringWithFormat:@"银联认证通讯中，请等待...(%lds)",_count];
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    //进度条加载完成
    _speedFlag = YES;
    self.myTitle = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];//获取当前页面的title
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
-(void)leftBtnClick{
    if (self.navigationController.topViewController == self) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    //    [self.navigationController popViewControllerAnimated:YES];
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

@end

